package com.lingkang.ngfile.service.impl;

import com.lingkang.ngfile.entity.NgUser;
import com.lingkang.ngfile.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component //交给spring托管，应为我们使用@Autowired注入了spring的接口
public class CustomUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户
        NgUser user = userService.getInfo(username);
        if (user == null) {
            throw new UsernameNotFoundException("access not found!");
        }
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        String[] roles = user.getUserRole().split(",");
        //查询拥有的角色
        for (String role : roles) {
            grantedAuthorities.add(new SimpleGrantedAuthority(role));
        }
        //spring5+要求密码加密，我这里传明文密码来加密
        String password = new BCryptPasswordEncoder().encode(user.getPassword());
        return new User(user.getUsername(), password, grantedAuthorities);
    }

}
